<template>
  <CDialog
    title="待确认规则"
    v-model:visible="dialogVisible"
    @confirm="dialogVisible = false"
    :show-cancel-button="false"
    confirm-text="关闭"
    :loading="loading"
    size="auto"
  >
    <div class="header">
      <div class="g-flex-start-center">
        <!-- 规则状态 -->
        <el-radio-group class="header-radio g-mr8" v-model="searchForm.status">
          <el-radio-button
            v-for="(item, index) in UnconfirmedRuleOptions"
            :key="index"
            :label="item.value"
          >
            {{ item.label }}</el-radio-button
          >
        </el-radio-group>
        <!-- 流类型 -->
        <CSelect v-model="searchForm.flowType" clearable placeholder="流类型">
          <el-option
            v-for="item in FlowTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </CSelect>
        <!-- 流名称 -->
        <el-input
          class="header-input g-mr8"
          placeholder="流名称"
          v-model="searchForm.flowName"
          clearable
          :suffix-icon="SearchIcon"
        />
        <!-- 关联次数 -->
        <el-input
          @wheel.stop.prevent
          type="number"
          class="header-input g-mr8"
          placeholder="关联次数"
          v-model="searchForm.relationNumGreater"
          clearable
          :suffix-icon="SearchIcon"
        />
      </div>

      <div id="factor-simple-page"></div>
    </div>

    <CTable
      :pagination="{
        teleport: '#factor-simple-page',
        layout: 'total, prev, slot, next'
      }"
      :tableFieldsSetting="tableFieldsSetting"
      :is-show-footer-bar="false"
      :height="myTableHeight"
      :loadData="loadData"
      ref="tableRef"
      selection
      border
    >
      <!-- 流类型 - slot -->
      <template #flowType="{ scope: { row } }">
        <p v-if="row.flowType">{{
          FlowTypesListMap[row.flowType as keyof typeof FlowTypesListMap]
        }}</p>
        <span v-else>-</span>
      </template>
      <!-- 核算标准 - slot -->
      <template #accountStandard="{ scope: { row } }">
        <span v-if="row.accountStandard">
          {{ StandardMap[row.accountStandard] }}
        </span>
        <span v-else>-</span>
      </template>
      <!-- 规则类型 - slot -->
      <template #ruleCategory="{ scope: { row } }">
        <span v-if="row.ruleCategory === 'UN'">-</span>
        <span v-else-if="row.ruleCategory === 'VDA_MDS'">VDA或MDS</span>
        <span v-else>
          {{ row.ruleCategory }}
        </span>
      </template>
      <!-- 关联因子 - slot -->
      <template #factorNo="{ scope: { row } }">
        <p v-ellTooltip="{ fetch: true }">{{ row.factorName }} / {{ row.factorNo }}</p>
      </template>
      <!-- 操作 - slot -->
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
    </CTable>

    <!-- 弹出层左下角按钮组 -->
    <template #footerLeft>
      <div>
        <!-- <el-button
          size="default"
          type="primary"
          @click="checkBatch(handleBatchGeneration, '请先选择需要生成的数据')"
          v-if="searchForm.status === UnconfirmedRuleEnum.WAIT_CONFIRM"
          >批量生成</el-button
        > -->
        <el-button
          size="default"
          type="primary"
          @click="checkBatch(handleBatchIgnore, '请先选择需要忽略的数据')"
          v-btnPermission="'DM_FLOW_MATCH_IGNORE'"
          v-if="searchForm.status === UnconfirmedRuleEnum.WAIT_CONFIRM"
          >批量忽略</el-button
        >
        <el-button
          size="default"
          type="primary"
          v-btnPermission="'DM_FLOW_MATCH_REMOVE_IGNORE'"
          @click="checkBatch(handleBatchRemove, '请先选择需要移除的数据')"
          v-if="searchForm.status === UnconfirmedRuleEnum.IGNORED"
          >批量移除</el-button
        >
      </div>
    </template>

    <!-- 生成规则弹出层 -->
    <GenerateRuleDialog
      v-model:visible="generateRuleVisible"
      :ruleNo="ruleNo"
      @refresh="refresh"
      @refreshFactorMatchRuleList="refreshFactorMatchRuleList"
    />
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'UnconfirmedRuleDialog'
};
</script>
<script lang="ts" setup>
import {
  defineComponent,
  h,
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  watch
} from 'vue';
import { CDialog } from '@/components/CDialog';
import { CTable } from '@/components/CTable/index';
import { CTableButtonGroup } from '@/components/CTable';
import { GIcon } from '@/components/GIcon/index';
import GenerateRuleDialog from './components/GenerateRuleDialog/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { useList } from './useList';
import { useWindowSize } from '@vueuse/core';
import type { TableButtonItem } from '@/components/CTable';
import { UnconfirmedRuleEnum } from '@/constants/system';
import { UnconfirmedRuleOptions, FlowTypesListMap, FlowTypeOptions } from '@/constants/enum';
import { CSelect } from '@/components/CSelect';
import { IGetUnconfirmedRuleListRes } from '@/apis/system/config/model/factorMatchingRule';
import {
  batchGenerate,
  batchIgnore,
  batchRemoveIgnore
} from '@/apis/system/config/factorMatchingRule';
import { StandardMap } from '@/constants/pcf';

const tableRef = ref();
const { tableFieldsSetting, searchForm, loadData } = useList(tableRef);
interface ConnectFactoryDialogProps {
  visible: boolean;
}
const props = withDefaults(defineProps<ConnectFactoryDialogProps>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh', 'queryUnConfirmedRule']);
const { createMessage, createConfirm } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});

watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      emit('queryUnConfirmedRule');
    }
  }
);

const loading = ref(false);

/**
 * 生成规则弹窗
 */
const generateRuleVisible = ref<boolean>(false);
const ruleNo = ref('');
/**
 * 单个/批量生成
 */
const handleBatchGeneration = async (
  currentData: IGetUnconfirmedRuleListRes | IGetUnconfirmedRuleListRes[]
) => {
  try {
    let ruleNoList = [] as string[];
    if (!(currentData instanceof Array)) {
      // 单个生成
      if (['VDA_MDS', 'UN'].includes(currentData.ruleCategory)) {
        // 规则类型为VDA或MDS的数据,打开弹窗
        generateRuleVisible.value = true;
        ruleNo.value = currentData.ruleNo;
        return;
      } else {
        // 其他类型的数据正常调用接口
        ruleNoList = [currentData.ruleNo];
      }
    } else {
      // 批量生成
      ruleNoList = currentData?.map((item: IGetUnconfirmedRuleListRes) => {
        return item.ruleNo;
      });
    }
    await batchGenerate({
      ruleNoList
    });
    createMessage.success('生成成功！');
    refreshFactorMatchRuleList();
    refresh();
  } catch (error) {
    console.log(error);
  }
};

const refresh = () => {
  tableRef.value?.refresh();
};

const refreshFactorMatchRuleList = () => {
  emit('refresh');
};

/**
 * 单个/批量忽略
 */
const handleBatchIgnore = async (
  currentData: IGetUnconfirmedRuleListRes | IGetUnconfirmedRuleListRes[]
) => {
  try {
    let ruleNoList = [];
    if (!(currentData instanceof Array)) {
      // 单个忽略
      ruleNoList = [currentData.ruleNo];
    } else {
      // 批量忽略
      ruleNoList = currentData?.map((item: IGetUnconfirmedRuleListRes) => {
        return item.ruleNo;
      });
    }
    await createConfirm('提示', '确认忽略该规则？', {
      iconType: 'warning',
      confirmButtonText: '忽略'
    });
    await batchIgnore({
      ruleNoList
    });
    createMessage.success('忽略成功！');
    tableRef.value?.refresh();
  } catch (error) {
    console.log(error);
  }
};

/**
 * 单个/批量移除
 */
const handleBatchRemove = async (
  currentData: IGetUnconfirmedRuleListRes | IGetUnconfirmedRuleListRes[]
) => {
  try {
    console.log('currentData', currentData);
    let ruleNoList = [];
    if (!(currentData instanceof Array)) {
      // 单个移除
      ruleNoList = [currentData.ruleNo];
    } else {
      // 批量移除
      ruleNoList = currentData?.map((item: IGetUnconfirmedRuleListRes) => {
        return item.ruleNo;
      });
    }
    await createConfirm('提示', '确认移除该规则？', {
      iconType: 'warning',
      confirmButtonText: '移除'
    });
    await batchRemoveIgnore({
      ruleNoList
    });
    createMessage.success('移除成功！');
    tableRef.value?.refresh();
  } catch (error) {
    console.log(error);
  }
};

/**
 * 校验批量是否有选择项
 */
const checkBatch = (fn: any, text: string) => {
  const $table = tableRef.value?.baseTableRef;
  if ($table) {
    if ($table.getCheckboxRecords().length > 0) {
      fn($table.getCheckboxRecords());
    } else {
      createMessage.warning(text);
    }
  }
};

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: IGetUnconfirmedRuleListRes): TableButtonItem[] {
  if (row.status !== UnconfirmedRuleEnum.IGNORED) {
    // 待确认
    return [
      {
        text: '生成规则',
        btnPermission: 'DM_FLOW_MATCH_GENERATE',
        onClick: () => handleBatchGeneration(row)
      },
      {
        text: '标记为忽略',
        btnPermission: 'DM_FLOW_MATCH_IGNORE',
        onClick: () => handleBatchIgnore(row)
      }
    ];
  } else {
    // 已忽略
    return [
      {
        text: '移除',
        btnPermission: 'DM_FLOW_MATCH_REMOVE_IGNORE',
        onClick: () => handleBatchRemove(row)
      }
    ];
  }
}

const { height: maxHeight } = useWindowSize();

const myTableHeight = computed(() => {
  // 42 搜索框高度  68 footer高度
  return maxHeight.value - 80 - 64 - 68 - 48;
});

// 搜索图标
const SearchIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-sousuo', style: 'font-size: 14px' });
  }
});
</script>

<style scoped lang="scss">
.header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  :deep(.el-select) {
    width: 128px;
    margin-right: 10px;
  }
  .header-unit {
    width: 128px;
    margin: 0 10px;
  }
  .header-input {
    width: 192px;
    height: 32px;
  }
}
.header-radio {
  height: 32px;
  border-radius: 3px;
  // border: 1px solid #f3f7fb;
  background: #f3f7fb;
  padding: 3px;
  :deep(.is-active .el-radio-button__inner) {
    background: #ffffff;
    border-radius: 3px;
    font-weight: 400;
    color: #0a1f33;
    &:before {
      content: '';
      width: 0;
    }
  }
  :deep(.el-radio-button__inner) {
    height: 26px;
    line-height: 22px;
    padding: 2px 12px;
    font-size: 14px;
    color: #7a8a99;
    border: none;
    position: relative;
    background: transparent;
    box-shadow: none;
    &:before {
      content: '';
      position: absolute;
      left: -1px;
      top: 7px;
      width: 1px;
      height: 12px;
      background: #e1e6eb;
    }
  }
  :deep(.is-active + .el-radio-button, .el-radio-button:first-child) {
    .el-radio-button__inner:before {
      content: '';
      width: 0;
    }
  }
}
</style>
